/**
 *
 * Created by 张栋 on 2017/2/22 18:36
 */
;(function($){
	$.fn.inputBox=function (options,refresh) {
		return this.each(function () {

			var defaults = {
				min:1,//最小值,设置为小数时会存在问题
				max:9999,//最大值
				maxLength:10,//整数部分最大长度,超长则直接截去
				decimalLength:0//小数部分长度,超长则直接截去,设置为0时,则只能输入整数,不能为小数
			};

			var $this = $(this);
			options = options || {};
			var opt = $.extend(defaults, options);
           
			if(!refresh){
				//生成样式
				var width=$this.width();
				var height=$this.height();
				var height1=height;
				var _root = this;
				width+=3;
				$this.css("border-style","none");
				$this.css("border-width","0px");
				$this.css("width",width-height1*2-7);
				$this.css("text-align","center");
				$this.css("outline","none");
				$this.css("vertical-align","middle");
				$this.css("line-height",height+"px");
				$this.wrap("<div   style='height:"+height+"px;border: 1px solid #CCC;'></div>");
				$this.before("<div  onselectstart='return false;' style='-moz-user-select:none;cursor:pointer;text-align:center;width:"+height1+"px;height:"+height1+"px;line-height:"+height1+"px;border-right-width: 1px;border-right-style: solid;border-right-color: #CCC;float:left'>-</div>");
				$this.after("<div   onselectstart='return false;' style='-moz-user-select:none;cursor:pointer;text-align:center;width:"+height1+"px;height:"+height1+"px;line-height:"+height1+"px;border-left-width: 1px;border-left-style: solid;border-left-color: #CCC;float:right'>+</div>");
			}

			$this.unbind("keyup");
			$this.keyup(function () {
				var v = $this.val();
				if(parseFloat(v) < opt.min){
					v=opt.min+"-";
				}
				var olength = v.length;
				v = v.replace(/[^\d\.]/g, '')
					.replace(/^0+/,'0')
					.replace(/\d*\.\d*/g,function (match,offset) {//处理小数点
						return ( offset!=0 || opt.decimalLength==0)?match.replace(/\./,''):match.replace(/^\./,'0.');
					})
					.replace(/^0+(\d+)/,'$1')
					.replace(new RegExp("(\\d+\\.\\d{"+opt.decimalLength+"})(\\d)"),'$1')
					.replace(new RegExp("(\\d{"+opt.maxLength+"})\\d+(\\.\\d*|)"),'$1$2');

				
				if(v!=""){
					var vnum =parseFloat(v);
					if(vnum < opt.min ){
						v= opt.min;
						$this.val(v);
					}else if(vnum>opt.max ){
						v=opt.max;
						$this.val(v);
					}
				}
				
				var nlength =v.length;
				if(olength!=nlength){
					if(v=="")v=opt.min;
					$this.val(v);
				}

			});

			if(!refresh){
				$this.prev().click(function(){
					var v = parseFloat($this.val());
					$this.val(v-1);
					$this.keyup();
				});

				$this.next().click(function(){
					var v = parseFloat($this.val());
					$this.val(v+1);
					$this.keyup();
				});
			}

		})
	};
})(jQuery);